﻿using System;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace ZilLion.TPO2O.SDK.EntityBase.JsonConverter
{
    public class ChinaDateTimeConverter : DateTimeConverterBase
    {

        public string FormatString { get; set; }

        public ChinaDateTimeConverter():this("yyyy-MM-dd HH:mm:ss")
        {

        }

        public ChinaDateTimeConverter(string formatString):base()
        {
            FormatString = formatString;
            _dtConverter = new IsoDateTimeConverter { DateTimeFormat = FormatString };
        }

        private readonly IsoDateTimeConverter _dtConverter;

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {

            try
            {
                return _dtConverter.ReadJson(reader, objectType, existingValue, serializer);
            }
            catch (Exception)
            {
                return DateTime.MinValue;
            }

        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            _dtConverter.WriteJson(writer, value, serializer);
        }
    }
}